package com.haoqizhe.kernel.activemq.producer.impl;

import com.haoqizhe.kernel.activemq.properties.ActivemqProperties;
import com.haoqizhe.kernel.activemq.common.ActivemqUtil;
import com.haoqizhe.kernel.activemq.producer.IProducer;
import com.haoqizhe.kernel.activemq.entity.SendParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.jms.Destination;
import java.util.Map;

/**
 * 所有关于activemq发送消息的类
 *
 * @author haoqizhe.li on 2017/6/18.
 */
@Service
@Slf4j
@EnableConfigurationProperties(ActivemqProperties.class)
public class Producer implements IProducer {

    @Autowired
    private ActivemqProperties properties;

    @Autowired
    @Qualifier(value="defaultJmsMessagingTemplate")
    private JmsMessagingTemplate defaultJmsMessagingTemplate;

    /**
     * 根据SendParam 发送消息
     * @param param
     * @author haoqizhe.li
     * @date 2017/6/21 9:24
     **/
    public void send(SendParam param)throws Exception{


        Object message = param.getMessage();

        Assert.hasLength(param.getDestinationName(),"destinationName must not be null or empty");
        Assert.notNull(message,"message must not be null");

        try{
            /**
             * 获取发送消息目的地
             */
            Destination destination = ActivemqUtil.getDestination(param,properties.getDestinationPrefix());
            /**
             * 设置消息头
             */
            Map<String,Object> headers = ActivemqUtil.getHeaders(param);

            JmsTemplate jmsTemplate = defaultJmsMessagingTemplate.getJmsTemplate();
            /**
             * 设置消息发送模板
             */
            jmsTemplate = ActivemqUtil.getSendJmsTemplate(param,jmsTemplate);

            defaultJmsMessagingTemplate.setJmsTemplate(jmsTemplate);
            /**
             * 发送消息
             */
            defaultJmsMessagingTemplate.convertAndSend(destination,message,headers);

        }catch(Exception e){
            log.error(e.getMessage(),e);
            Assert.state(false,e.getMessage());
        }
    }
}
